/*
 * Atomic Predicates for Transformers
 * 
 * Copyright (c) 2015 UNIVERSITY OF TEXAS AUSTIN. All rights reserved. Developed
 * by: HONGKUN YANG and SIMON S. LAM http://www.cs.utexas.edu/users/lam/NRL/
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * with the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimers.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimers in the documentation
 * and/or other materials provided with the distribution.
 * 
 * 3. Neither the name of the UNIVERSITY OF TEXAS AUSTIN nor the names of the
 * developers may be used to endorse or promote products derived from this
 * Software without specific prior written permission.
 * 
 * 4. Any report or paper describing results derived from using any part of this
 * Software must cite the following publication of the developers: Hongkun Yang
 * and Simon S. Lam, Scalable Verification of Networks With Packet Transformers
 * Using Atomic Predicates, IEEE/ACM Transactions on Networking, October 2017,
 * Volume 25, No. 5, pages 2900-2915 (first published as IEEE Early Access
 * Article, July 2017, Digital Object Identifier: 10.1109/TNET.2017.2720172).
 * 
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH
 * THE SOFTWARE.
 */
package transformer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

import common.BDDACLWrapper;
import common.Fields;
import common.PositionTuple;

public class Net implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = -8282858401497816491L;
    BDDACLWrapper bddengine;
    String name;
    HashMap<String, Box> boxes;
    ArrayList<String> edgerouters;
    HashSet<PositionTuple> activeports;
    
    public ArrayList<NATBox> add_nat(int nat_num) {
        return add_nat(nat_num, false);
    }

    /**
     * 
     * @param nat_num
     * @param random - whether to randomly add nats to routers
     * @return
     */
    public ArrayList<NATBox> add_nat(int nat_num, boolean random)
    {
        ArrayList<NATBox> nats = new ArrayList<NATBox>();
        int num_nat_to_ad = Math.min(nat_num, edgerouters.size());
        System.out.println("adding "+ num_nat_to_ad + " nats...");
        
        if(random) {
            Collections.shuffle(edgerouters);
        }
        
        for(int i = 0; i < num_nat_to_ad; i++)
        {
            Device d = (Device) boxes.get(edgerouters.get(i));
            System.out.println("add NAT to " + d.name);

            PositionTuple pt_r = d.add_nat();
            int old_pkt = d.fwbdds.get(pt_r.getPortName());
            // 
            old_pkt = bddengine.set_field_bit(Fields.mpls_label, old_pkt, false);

            bddengine.ref(old_pkt);

            NATBox nat = new NATBox("nat"+i);
            // 3232235520 = 192.168.0.0
            nat.add_entry_out(old_pkt, bddengine.get_field_bdd(Fields.dst_ip), 
                    bddengine.encodeDstIPPrefix(3232235520L+i, 32));

            PositionTuple pt_nat = new PositionTuple(nat.getName(), NATBox.port_out);
            addTopology(pt_r, pt_nat);
            addBox(nat);
            nats.add(nat);
        }
        return nats;
    }

    public NATBox add_nat(String dname)
    {
        NATBox nat = null;
        for(int i = 0; i < edgerouters.size(); i++)
        {
            Device d = (Device) boxes.get(edgerouters.get(i));

            if(dname.equals(d.name))
            {
                System.out.println("add NAT to " + d.name);

                PositionTuple pt_r = d.add_nat();
                int old_pkt = d.fwbdds.get(pt_r.getPortName());
                // 
                old_pkt = bddengine.set_field_bit(Fields.mpls_label, old_pkt, false);

                bddengine.ref(old_pkt);

                nat = new NATBox("nat"+i);
                // 3232235520 = 192.168.0.0
                nat.add_entry_out(old_pkt, bddengine.get_field_bdd(Fields.dst_ip), 
                        bddengine.encodeDstIPPrefix(3232235520L+i, 32));

                PositionTuple pt_nat = new PositionTuple(nat.getName(), NATBox.port_out);
                addTopology(pt_r, pt_nat);
                addBox(nat);
            }
        }

        return nat;
    }


    // device|port - device|port
    HashMap<PositionTuple, HashSet<PositionTuple>> topology;

    public HashSet<PositionTuple> LinkTransfer(PositionTuple pt)
    {
        //System.out.println();
        return topology.get(pt);
    }

    public HashMap<PositionTuple, HashSet<PositionTuple>> get_topology()
    {
        return topology;
    }

    /**
     * 
     * @param dname
     * @return all links connected to device dname
     */
    public ArrayList<PositionTuple> get_all_links(String dname)
    {
        ArrayList<PositionTuple> links = new ArrayList<PositionTuple> ();

        for(PositionTuple pt : topology.keySet())
        {
            if(pt.getDeviceName().equals(dname))
            {
                for(PositionTuple pt2 : topology.get(pt))
                {
                    links.add(pt);
                    links.add(pt2);
                }
            }
        }

        return links;
    }

    public Box getBox(String dname)
    {
        return boxes.get(dname);
    }

    public Collection<Box> getAllBoxes()
    {
        return boxes.values();
    }

    public HashSet<PositionTuple> getallactiveports()
    {
        return activeports;
    }

    public void setactiveports()
    {
        activeports = new HashSet<PositionTuple> (topology.keySet());
        System.out.println(activeports.size()+" active ports");
    }

    public void addTopology(String d1, String p1, String d2, String p2)
    {
        PositionTuple pt1 = new PositionTuple(d1, p1);
        PositionTuple pt2 = new PositionTuple(d2, p2);
        // links are two way
        addTopology(pt1, pt2);
    }

    public void addTopology(PositionTuple pt1, PositionTuple pt2)
    {
        if(!topology.containsKey(pt1))
        {
            topology.put(pt1, new HashSet<PositionTuple>());
        }
        if(!topology.containsKey(pt2))
        {
            topology.put(pt2, new HashSet<PositionTuple>());
        }
        topology.get(pt1).add(pt2);
        topology.get(pt2).add(pt1);
    }

    public void removeTopology(PositionTuple pt1, PositionTuple pt2)
    {
        if(topology.containsKey(pt1))
        {
            topology.get(pt1).remove(pt2);
        }
        if(topology.containsKey(pt2))
        {
            topology.get(pt2).remove(pt1);
        }
    }

    /**
     * usually called with addTopology
     */
    public void addBox(Box b)
    {
        boxes.put(b.getName(), b);
    }
}
